
// Define the global namespace for the application and the functions/methods within it (in case it's not already set)
if (!window.FrontSuite) FrontSuite = {};
if (!FrontSuite.util) FrontSuite.util = {};
if (!FrontSuite.util.jquery) FrontSuite.util.jquery = {};

FrontSuite.util.jquery.login = function (user_token, password, duration, callback) {
    var apps_urldir             = FrontSuite.options.apps_urldir;
    var client_connection_token = FrontSuite.connection.client_connection_token;
    $.ajax({
        url       : apps_urldir+'/sitefront/front-framework/api.php/service/auth/user_auth_info',
        type      : 'POST',
        data      : {'user_token' : user_token, 'client_connection_token' : client_connection_token},
        dataType  : 'json',    // type of returned data
        context   : FrontSuite,
        success : function(user_auth_info_response, status, xhr) {   // change to "done:" as of jQuery 1.8
            if (user_auth_info_response.success == true) {
            var user_salt           = user_auth_info_response.user_salt;
            var algorithm           = user_auth_info_response.algorithm;
            var algorithm_option    = user_auth_info_response.algorithm_option;
            var current_date        = new Date();
            var current_time        = current_date.getTime();              // returns milliseconds since 1970-01-01 00:00:00 UTC
            var session_expire_time = current_time + duration*3600*1000;   // expire in the specified number of hours
            var session_expire_date = new Date(session_expire_time);
            var session_expire_dttm = session_expire_date.toISOString();
            session_expire_dttm     = session_expire_dttm.replace(/\.[0-9]+Z$/,'');
            session_expire_dttm     = session_expire_dttm.replace(/T/,' ');
            var password_hash       = FrontSuite.util.makePasswordHash(algorithm, algorithm_option, password, user_salt);
            var auth_token          = FrontSuite.util.makeAuthToken(password_hash, session_expire_dttm, client_connection_token);

            $.ajax({
                url       : apps_urldir+'/sitefront/front-framework/api.php/service/auth/login',
                type      : 'POST',
                data      : {'user_token': user_token, 'session_expire_dttm': session_expire_dttm, 'auth_token': auth_token, 'option': 'authdata'},
                dataType  : 'json',    // type of returned data
                context   : FrontSuite,
                success : function(login_response, status, xhr) {   // change to "done:" as of jQuery 1.8
                    if (login_response.success && login_response.user.user_token != 'guest') {
                        FrontSuite.session.user_token          = user_token;
                        FrontSuite.session.auth_token          = auth_token;
                        FrontSuite.session.session_expire_dttm = session_expire_dttm;
                        FrontSuite.session.group_id            = login_response.user.user_id;
                        FrontSuite.session.app_id              = 0;
                        if (FrontSuite.session.authdata)       delete FrontSuite.session.authdata;
                        FrontSuite.session.authdata            = login_response;
                        if (callback) (callback)(true);
                        else FrontSuite.util.jquery.message('Login Successful', 'Login Successful'+user_auth_info_response.message+')');
                    }
                    else {
                        if (callback) (callback)(false, 'Login Failed: Username or Password is incorrect');
                        else FrontSuite.util.jquery.message('Login Failed', 'Login Failed: Username or Password is incorrect');
                    }
                },
                error: function(xhr, status, error) {
                    if (callback) (callback)(false, 'Login Failed: ' + response.status);
                    else FrontSuite.util.jquery.message('Login Failed', 'Login Failed: ' + response.status);
                }
            });
            }
            else {
                if (callback) (callback)(false, 'Login Failed: the username or password was not correct. Perhaps you need to Register first.');
            }
        },
        error: function(xhr, status, error) {
            if (callback) (callback)(false, 'Login Failed: ' + response.status);
            else FrontSuite.util.jquery.message('Login Failed', 'Login Failed: ' + response.status);
        }
    });
};

FrontSuite.util.jquery.register = function (email, password, userData, callback) {
    var apps_urldir             = FrontSuite.options.apps_urldir;
    var client_connection_token = FrontSuite.connection.client_connection_token;
    userData.client_connection_token = client_connection_token;
    $.ajax({
        url       : apps_urldir+'/sitefront/front-framework/api.php/service/auth/reserve_user',
        type      : 'POST',
        data      : userData,
        dataType  : 'json',    // type of returned data
        context   : FrontSuite,
        success : function(reserve_user_response, status, xhr) {   // change to "done:" as of jQuery 1.8
            if (reserve_user_response.success == false) {
                if (callback) (callback)(false, 'Registration Failed: '+reserve_user_response.message);
                else FrontSuite.util.jquery.message('Registration Failed', 'Registration Failed: ('+reserve_user_response.message+')');
            }
            else {
                var user_salt           = reserve_user_response.user_salt;
                var algorithm           = reserve_user_response.algorithm;
                var algorithm_option    = reserve_user_response.algorithm_option;
                var username            = reserve_user_response.username;
                var password_hash       = FrontSuite.util.makePasswordHash(algorithm, algorithm_option, password, user_salt);
                var crypt_password_hash = FrontSuite.util.encrypt(client_connection_token, password_hash);   // use the client_connection_token to encrypt the password_hash
                userData.username = username;
                userData.email    = email;
                userData.x        = crypt_password_hash;
                if (userData.password) delete userData.password;

                $.ajax({
                    url       : apps_urldir+'/sitefront/front-framework/api.php/service/auth/register',
                    type      : 'POST',
                    data      : userData,
                    dataType  : 'json',    // type of returned data
                    context   : FrontSuite,
                    success : function(registration_response, status, xhr) {   // change to "done:" as of jQuery 1.8
                        if (registration_response.success == true) {
                            if (callback) (callback)(true, registration_response.message);
                            else FrontSuite.util.jquery.message('Registration Success', 'The First Part of Registration has been Successful');
                        }
                        else {
                            if (callback) (callback)(false, 'Registration Failed: '+registration_response.message);
                            else FrontSuite.util.jquery.message('Registration Failed', 'Registration Failed: ('+registration_response.message+')');
                        }
                    },
                    error: function(xhr, status, error) {
                        if (callback) (callback)(false, 'Registration Failed (due to technical malfunction): ('+error+')');
                        else FrontSuite.util.jquery.message('Registration Failed', 'Registration Failed (due to technical malfunction): ('+error+')');
                    }
                });
            }
        },
        error: function(xhr, status, error) {
            if (callback) (callback)(false, 'Registration Failed (due to technical malfunction on reserve_user): '+error);
        }
    });
};

FrontSuite.util.jquery.changeGroupOrApp = function (group_id, app_id, callback) {
    var apps_urldir      = FrontSuite.options.apps_urldir;

    //$.ajax({
    //    url       : apps_urldir+'/sitefront/front-framework/api.php/service/auth/login',
    //    type      : 'POST',
    //    data      : {'client_connection_token': client_connection_token,
    //                 'recaptcha_response_field': userData.recaptcha_response_field,
    //                 'recaptcha_challenge_field': userData.recaptcha_challenge_field},
    //    dataType  : 'json',    // type of returned data
    //    context   : FrontSuite,
    //    success : function(reserve_user_response, status, xhr) {}   // change to "done:" as of jQuery 1.8
    // });

    $.ajax({
        url       : apps_urldir+'/sitefront/front-framework/api.php/service/auth/login',
        type      : 'POST',
        data      : {'user_token': FrontSuite.session.user_token,
                     'session_expire_dttm': FrontSuite.session.session_expire_dttm,
                     'auth_token': FrontSuite.session.auth_token,
                     'group_id': group_id,
                     'app_id': app_id,
                     'option': 'authdata'},
        dataType  : 'json',    // type of returned data
        context   : FrontSuite,
        success : function(login_response, status, xhr) {   // change to "done:" as of jQuery 1.8
            if (login_response.success) {
                FrontSuite.session.group_id           = login_response.group_id;
                FrontSuite.session.app_id             = login_response.app_id;
                if (FrontSuite.session.authdata) delete FrontSuite.session.authdata;
                var session_expire_date               = new Date(FrontSuite.session.session_expire_dttm);
                FrontSuite.session.authdata           = login_response;
                if (callback) (callback)(true);
                else FrontSuite.util.jquery.message('Group Change Successful', 'Group Change Successful');
            }
            else {
                if (callback) (callback)(false, 'Group Change Failed: Username or Password is incorrect');
                else FrontSuite.util.jquery.message('Group Change Failed', 'Group Change Failed: Username or Password is incorrect');
            }
        },
        error: function(xhr, status, error) {
            if (callback) (callback)(false, 'Group Change Failed: ' + response.status);
            else FrontSuite.util.jquery.message('Group Change Failed', 'Group Change Failed: ' + response.status);
        }
    });
};

FrontSuite.util.jquery.logout = function (callback) {
    var apps_urldir         = FrontSuite.options.apps_urldir;
    var session_expire_dttm = '2038-01-01T00:00:00Z';
    var session_expire_date = new Date(session_expire_dttm);

    $.ajax({
        url       : apps_urldir+'/sitefront/front-framework/api.php/service/auth/logout',
        type      : 'POST',
        data      : {},
        dataType  : 'json',    // type of returned data
        context   : FrontSuite,
        success : function(logout_response, status, xhr) {   // change to "done:" as of jQuery 1.8
            if (logout_response.success) {
                FrontSuite.session.user_token          = logout_response.user.user_token;
                FrontSuite.session.session_expire_dttm = session_expire_dttm;
                FrontSuite.session.auth_token          = 'xxxxxx';
                FrontSuite.session.group_id            = logout_response.user.group_id || logout_response.user.default_group_id;
                FrontSuite.session.app_id              = logout_response.user.app_id || logout_response.user.default_app_id;
                if (FrontSuite.session.authdata)       delete FrontSuite.session.authdata;
                FrontSuite.session.authdata            = logout_response;
                if (callback) (callback)(true);
                else FrontSuite.util.jquery.message('Logout Successful', 'Logout Successful');
            }
            else {
                if (callback) (callback)(false, 'Logout Failed');
                else FrontSuite.util.jquery.message('Logout Failed', 'Logout Failed');
            }
        },
        error: function(xhr, status, error) {
            if (callback) (callback)(false, 'Login Failed: ' + response.status);
            else FrontSuite.util.jquery.message('Logout Failed', 'Logout Failed: ' + response.status);
        }
    });
};

//FrontSuite.util.jquery.refresh_state = function (callback) {
//    var apps_urldir             = FrontSuite.options.apps_urldir;
//    var client_connection_token = FrontSuite.connection.client_connection_token;
//    $.ajax({
//        url       : apps_urldir+'/sitefront/front-framework/api.php/service/auth/login',
//        type      : 'POST',
//        data      : {'user_token': user_token, 'session_expire_dttm': session_expire_dttm, 'auth_token': auth_token, 'option': 'authdata'},
//        dataType  : 'json',    // type of returned data
//        context   : FrontSuite,
//        success : function(state_response, status, xhr) {   // change to "done:" as of jQuery 1.8
//            if (state_response.success && state_response.user.user_token != 'guest') {
//                FrontSuite.session.user_token          = user_token;
//                FrontSuite.session.auth_token          = auth_token;
//                FrontSuite.session.session_expire_dttm = session_expire_dttm;
//                FrontSuite.session.group_id            = state_response.user.user_id;
//                FrontSuite.session.app_id              = 0;
//                if (FrontSuite.session.authdata)       delete FrontSuite.session.authdata;
//                FrontSuite.session.authdata            = state_response;
//                if (callback) (callback)(true);
//                else FrontSuite.util.jquery.message('Login Successful', 'Login Successful'+state_response.message+')');
//            }
//            else {
//                if (callback) (callback)(false, 'Login Failed: Username or Password is incorrect');
//                else FrontSuite.util.jquery.message('Login Failed', 'Login Failed: Username or Password is incorrect');
//            }
//        },
//        error: function(xhr, status, error) {
//            if (callback) (callback)(false, 'Login Failed: ' + response.status);
//            else FrontSuite.util.jquery.message('Login Failed', 'Login Failed: ' + response.status);
//        }
//    });
//};

FrontSuite.util.jquery.modify_session = function (session_data, callback) {
    var apps_urldir         = FrontSuite.options.apps_urldir;
    var session_expire_dttm = '2038-01-01T00:00:00Z';
    var session_expire_date = new Date(session_expire_dttm);

    $.ajax({
        url       : apps_urldir+'/sitefront/front-framework/api.php/service/auth/modifySession',
        type      : 'POST',
        data      : session_data,
        dataType  : 'json',    // type of returned data
        context   : FrontSuite,
        success : function(modify_session_response, status, xhr) {   // change to "done:" as of jQuery 1.8
            if (modify_session_response.success) {
                var key;
                for (key in session_data) {
                    FrontSuite.session[key] = session_data[key];
                }
                if (callback) (callback)(true);
                else FrontSuite.util.jquery.message('Modify-Session Successful', 'Modify-Session Successful');
            }
            else {
                if (callback) (callback)(false, 'Modify-Session Failed');
                else FrontSuite.util.jquery.message('Modify-Session Failed', 'Modify-Session Failed');
            }
        },
        error: function(xhr, status, error) {
            if (callback) (callback)(false, 'Login Failed: ' + response.status);
            else FrontSuite.util.jquery.message('Modify-Session Failed', 'Modify-Session Failed: ' + response.status);
        }
    });
};

// ASYNCHRONOUS: slips in a message that fades away
// code based on http://dev.sencha.com/deploy/ext-4.0.0/examples/message-box/msg-box.html
FrontSuite.util.jquery.message = function (title, messageText, duration) {
    // TEMPORARY IMPLEMENTATION
//    alert(messageText);
    // IMPLEMENTATION UNDER DEVELOPMENT
//    if (!FrontSuite.util.jquery.msgDiv) {
//        var msgDiv = document.createElement("div");
//        msgDiv.id = 'msg-div';
//        var body = document.body;
//        body.insertBefore(msgDiv, body.firstChild);
//        FrontSuite.util.jquery.msgDiv = msgDiv;
//    }
//    if (!duration) duration = 1500;
//    var msgBox = $('<div class="msg"><h3>' + title + '</h3><p>' + messageText + '</p></div>');
//    $('#msg-div').append(msgBox);

    // EXTRA JUNK: TO BE DELETED ONCE THE IMPLEMENTATION IS DONE
    // msgBox.hide();
    //msgBox.slideDown({
    //    'duration': duration
    //});
    //jvar parser = new DOMParser()
    //jvar msgDocument = parser.parseFromString(msgBox, "text/xml");
    //jvar msgElement = msgDocument.firstChild;
    //console.log(msgElement);
    //jFrontSuite.util.jquery.msgDiv.appendChild(msgElement);
    //msgElement.hide();
    //msgElement.slideIn('t').ghost('t', {delay: duration, remove: true});
};

// SYNCHRONOUS: Pops up a dialog box
FrontSuite.util.jquery.notify = function (args) {
    var message;
    var typeof_args = typeof args;
    if (args && typeof_args == 'object') message = args.message;
    else                                 message = args;
    alert(message);
};

// SYNCHRONOUS: Pops up a dialog box
FrontSuite.util.jquery.error = function (args) {
    var message;
    var typeof_args = typeof args;
    if (args && typeof_args == 'object') message = args.message;
    else                                 message = args;
    alert(message);
};


